﻿CREATE TRIGGER yaf_Active_insert
ON dbo.yaf_Active
FOR INSERT
AS
    BEGIN
        DECLARE  @BoardID  INT,
                 @count    INT,
                 @countStr NVARCHAR(255),
                 @dtStr    NVARCHAR(255),
                 @max      INT,
                 @maxStr   NVARCHAR(255)
        -- Assumes only one row was inserted - shouldn't be a problem?
        SELECT @BoardID = BoardID
        FROM   inserted
        SELECT @count = COUNT(DISTINCT IP)
        FROM   yaf_Active WITH (nolock)
        WHERE  BoardID = @BoardID
        SELECT @maxStr = CAST(VALUE AS NVARCHAR)
        FROM   yaf_Registry
        WHERE  BoardID = @BoardID
        AND Name = N'maxusers'
        SELECT @max = CAST(@maxStr AS INT)
        SELECT @countStr = CAST(@count AS NVARCHAR)
        SELECT @dtStr = CONVERT(NVARCHAR,Getdate(),126)
        IF @@ROWCOUNT = 0
        BEGIN
            INSERT INTO yaf_Registry
                       (BoardID,
                        Name,
                        VALUE)
            VALUES     (@BoardID,
                        N'maxusers',
                        CAST(@countStr AS NTEXT))
            INSERT INTO yaf_Registry
                       (BoardID,
                        Name,
                        VALUE)
            VALUES     (@BoardID,
                        N'maxuserswhen',
                        CAST(@dtStr AS NTEXT))
        END
        ELSE
        IF @count > @max
        BEGIN
            UPDATE yaf_Registry
            SET    VALUE = CAST(@countStr AS NTEXT)
            WHERE  BoardID = @BoardID
            AND Name = N'maxusers'
            UPDATE yaf_Registry
            SET    VALUE = CAST(@dtStr AS NTEXT)
            WHERE  BoardID = @BoardID
            AND Name = N'maxuserswhen'
        END
    END


